import 'dart:convert';
import 'package:base_flutter/base_flutter.dart' as b;
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/a_yyt/models/handover_new_area_entity.dart';
import 'package:ls_work/a_yyt/models/handover_new_entity.dart';
import 'package:ls_work/a_yyt/page/handover_area_detail_page.dart';
import 'package:ls_work/common/common.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/net/post_request.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/util/event_bus.dart';
import 'package:ls_work/util/toast.dart';



class HandoverAreaPage extends StatefulWidget {
  final HandoverNewInfo? info;
  HandoverAreaPage({Key? key, this.info});
  @override
  _HandoverAreaPageState createState() => _HandoverAreaPageState();
}

class _HandoverAreaPageState extends State<HandoverAreaPage>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  PageController _pageController = PageController(initialPage: 0);
  TabController? _tabController;
  HandoverNewAreaEntity? detailModel;
  List<HandoverNewAreaInfo> dataList = [];
  int _pageIndex = 0;

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _tabController = new TabController(vsync: this, length: dataList.length);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      /// 接口请求
      _fectData();
    });
  }

  @override
  void dispose() {
    _tabController?.dispose();
    _pageController.dispose();
    eventBus.off(Constant.eventHandoverRefresh);
    super.dispose();
  }

  _onPageChange(int index) {
    _pageIndex = index;
    _tabController?.animateTo(index);
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      appBar: AppBar(
        elevation: 0.5,
        actions: [
          TextButton(
            onPressed: _fectHandoverRefresh,
            child: Text(
              '刷新',
              style: TextStyle(fontSize: 18, color: Colors.blue),
            ),
          )
        ],
        title: TabBar(
          onTap: (index) {
            if (!mounted) {
              return;
            }
            _pageController.jumpToPage(index);
          },
          isScrollable: true,
          controller: _tabController,
          labelStyle: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
          indicatorSize: TabBarIndicatorSize.label,
          unselectedLabelColor: Colours.text_gray,
          unselectedLabelStyle: TextStyles.textGray16,
          labelColor: Colours.text_dark,
          indicatorColor: Colours.app_main,
          indicatorPadding: EdgeInsets.only(bottom: 5),
          tabs: dataList.map((e) => Tab(text: '${e.name}')).toList(),
        ),
      ),
      body: PageView.builder(
        key: const Key('pageView'),
        itemCount: dataList.length,
        onPageChanged: _onPageChange,
        controller: _pageController,
        itemBuilder: (BuildContext context, int index) {
          return HanoverAreaDetailPage(
            areaId: dataList[index].id,
            reportDate: widget.info?.reportDate,
            dutyType: widget.info?.dutyType,
          );
        },
      ),
    );
  }

  _fectData() {
    var map = {
      'reportDate': widget.info?.reportDate,
      'dutyType': widget.info?.dutyType,
    };
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.shiftingDutyArea}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            HandoverNewAreaEntity model =
                HandoverNewAreaEntity.fromJson(map['data']);
            if ((model.areas??[]).length > 0) {
              setState(() {
                detailModel = model;
                dataList = model.areas??[];
                _tabController =
                    new TabController(vsync: this, length: dataList.length);
              });
            } else {
              Toast.show("没有更多数据");
            }
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///刷新
  _fectHandoverRefresh() {
    var map = {'id': widget.info?.id};
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance
        .getDio()
        .post('${HttpApi.handoverRefresh}', data: map,options: PostRequest.urlencodedHeader)
        .then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());
        if (map["code"].toString() == "0") {
          eventBus
              .emit(Constant.eventHandoverRefresh, [dataList[_pageIndex].id]);
          Toast.show("没有更多数据");
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }
}
